package com.zhny.iot.syb.dish.plugin;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.iot.syb.dish.plugin.model.DishStoreEntry;
import io.netty.util.internal.StringUtil;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DishDevice extends ModbusNumDevice<DishStoreEntry> {
    public DishDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (engine, factory, centerFacilities, entity);
    }

    @Override
    public DishStoreEntry decode(ModemResponseMessage modemResponseMessage) {
        logger.info("start dish  decode");
        logger.info ("before device real data {}--{}",this.getDeviceEntity ().getPropertyInfo (),this.getDeviceEntity ().getProperties ());
        String json = this.getDeviceEntity ().getProperties ();
        DishStoreEntry entry = new DishStoreEntry();
        int waterless = modemResponseMessage.getData().readUnsignedShort();
        Map<String,String> valueMap = mapTo(json);
        if(valueMap == null)
            entry.setHeight("--");
        int value = Integer.valueOf (valueMap.get ("height"));

        int result = waterless > value?0:value - waterless;
//        int depth = StringUtils.isNullOrEmpty(config.getDepth())?0:Integer.parseInt(config.getDepth());
        entry.setHeight (String.valueOf (result));
        logger.info("dish end decode {},new value {}",waterless,result);
        return entry;
    }

    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData().readableBytes()== 2;
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory().getRequestMessage(getConfig());
    }

    @Override
    protected void disposable() {

    }

     private Map<String,String> mapTo(String body){
        if(StringUtil.isNullOrEmpty (body))
            return null;
        ObjectMapper mapper=new ObjectMapper ();
        try {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            Map<String,String> obj=mapper.readValue (body,new TypeReference<Map<String,String>> () {});
            return obj;
//            return mapper.writeValueAsString(this);
        } catch (IOException e) {
            return null;
        }
    }
}
